<script setup lang="ts">
// 引入xlsx解析和格式判断方法
import { checkXLSX, parseXLSX } from '../api'
import {
  FormInstance,
  FormRules,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadRequestOptions,
  ElMessage,
  genFileId,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElButton,
  ElInput,
  ElUpload
} from 'element-plus'
import { reactive, ref } from 'vue'
//引入获取任务的请求的方法
import { uploadResult } from '@/api/bianmafuma'
import { onMounted } from 'vue'

import { Table, TableColumn } from '@/components/Table'
import axios from 'axios'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

interface MissionForm {
  taskName: string
  department: string
  file: UploadRawFile | null
}

const rules = reactive<FormRules<MissionForm>>({
  taskName: [
    {
      required: true,
      message: '必须填写任务名称',
      trigger: 'blur'
    }
  ],
  department: [
    {
      required: true,
      message: '必须选择数据归属部门',
      trigger: 'change'
    }
  ],
  file: [
    {
      required: true,
      message: '必须上传文件',
      trigger: 'change'
    }
  ]
})

const formEl = ref<FormInstance>()

defineProps({
  departments: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['closeDialog'])

// 申请表单
const missionForm = reactive<MissionForm>({
  taskName: '',
  department: '',
  file: null
})

// 预览表格
const previewTableData = ref([])

const columns: TableColumn[] = [
  {
    field: 'id',
    label: '*实体业务ID',
    // width: 100,
    headerAlign: 'center'
  },
  {
    field: 'name',
    label: '*实体名称',
    // width: 100,
    headerAlign: 'center'
  },
  {
    field: 'classifyName',
    label: '分类名称',
    // width: 100,
    headerAlign: 'center'
  },
  {
    field: 'classifyCode',
    label: '*分类码'
  },
  {
    field: 'regionName',
    label: '所属行政区',
    // width: 80,
    headerAlign: 'center'
  },
  {
    field: 'regionCode',
    label: '*行政区划码',
    // width: 80,
    headerAlign: 'center'
  },
  {
    field: 'des',
    label: '区域范围说明'
  },
  {
    field: 'lon',
    label: '*经度',
    // width: 100,
    headerAlign: 'center'
  },
  {
    field: 'lat',
    label: '*纬度',
    // width: 100,
    headerAlign: 'center'
  },
  {
    field: 'alt',
    label: '高程'
  },
  {
    field: 'addition',
    label: '备注'
  }
]

// 下载模板表格
const downloadTemplate = async () => {
  axios
    .get('/xlsx/template.xlsx', {
      responseType: 'blob'
    })
    .then((res) => {
      const downloadUrl = URL.createObjectURL(new Blob([res.data]))
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = downloadUrl
      a.download = '模板文件.xlsx'
      const event = new MouseEvent('click')
      a.dispatchEvent(event)
    })
}

// 获取上传组件实例
const upload = ref<UploadInstance>()

// 清空申请表
const clearUpload = () => {
  upload.value!.clearFiles()
  previewTableData.value = []
  missionForm.taskName = ''
  missionForm.department = ''
}

// 上传文件的回调
const handleChange: UploadProps['onChange'] = (uploadFile, _uploadFiles) => {
  console.log(uploadFile)
  missionForm.file = uploadFile.raw!
  parseXLSX(uploadFile.raw)
    .then((data) => {
      console.log(data)
      if (!Array.isArray(data)) {
        upload.value!.clearFiles()
        upload.value!.abort(uploadFile)
        ElMessage.error('上传文件格式或内容错误，请检查后重新上传文件')
      }

      if (checkXLSX(data as Array<any>)) {
        ; (data as Array<any>)!.shift()

        data = (data as Array<any>).slice(0, 10)
        const res: any[] = []
        for (const row of data as Array<any>) {
          if (row.length == 0) continue
          res.push({
            id: row[0] || '',
            name: row[1] || '',
            classifyName: row[2] || '',
            classifyCode: row[3] || '',
            regionName: row[4] || '',
            regionCode: row[5] || '',
            des: row[6] || '',
            lon: row[7] || '',
            lat: row[8] || '',
            alt: row[9] || '',
            addition: row[10] || ''
          })
        }
        previewTableData.value = res as any
      } else {
        upload.value!.clearFiles()
        upload.value!.abort(uploadFile)
        ElMessage.error('上传文件格式或内容错误，请检查后重新上传文件')
      }
      // 在这里可以对提取的数据进行进一步处理
    })
    .catch((error) => {
      console.error(error)
    })
}

// 覆盖上传文件的回调
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

// 删除上传文件的回调
const handleRemove: UploadProps['onRemove'] = (_file, _fileList) => {
  upload.value?.clearFiles()
  missionForm.file = null
  previewTableData.value = []
}

const handleUpload = async (_file: UploadRequestOptions) => {
  const data = {
    file: missionForm.file,
    department: missionForm.department,
    taskName: missionForm.taskName
  }

  uploadResult(data)

  ElMessage.success('申请成功')
  clearUpload()
  emit('closeDialog')
  // getMissionInfo()
}

// 提交上传文件的回调
const submitUpload = async () => {
  if (!formEl.value) return

  await formEl.value!.validate((valid, _fields) => {
    if (valid) {
      upload.value!.submit()
    } else {
    }
  })
}

defineExpose({
  submitUpload
})

onMounted(() => {
  clearUpload()
  missionForm.department = userStore.userInfo?.role === 'admin' ? '' : userStore.userInfo!.username
})
</script>

<template>
  <ElForm ref="formEl" :model="missionForm" label-width="auto" style="max-width: 450px" :rules="rules">
    <ElFormItem label="申请名称" prop="taskName">
      <ElInput v-model="missionForm.taskName" />
    </ElFormItem>
    <ElFormItem label="数据归属部门" prop="department">
      <ElSelect v-model="missionForm.department" placeholder="请选择数据归属部门"
      :disabled="userStore.userInfo?.role !== 'admin'"
      >
        <ElOption v-for="item in Object.keys(departments).map((key) => ({
    label: departments[key],
    value: key
  }))" :key="item.label" :label="item.label" :value="item.value" />
      </ElSelect>
    </ElFormItem>
    <ElFormItem label="数据文件上传" prop="file">
      <!-- :on-exceed="handleExceed" -->
      <ElUpload ref="upload" class="upload-demo" action="#" :limit="1" accept=".xlsx" :auto-upload="false"
        :http-request="handleUpload" :on-change="handleChange" :on-exceed="handleExceed" :on-remove="handleRemove">
        <template #trigger>
          <ElButton type="primary">选择文件</ElButton>
        </template>
        <template #default>
          <ElButton type="success" @click="downloadTemplate"
            style="margin-top: -2.5px; margin-left: 10px">下载模板</ElButton>
        </template>
        <template #tip>
          <div class="el-upload__tip text-red"> 只能上传一个文件，再次上传会覆盖前一个文件 </div>
        </template>
      </ElUpload>
    </ElFormItem>
  </ElForm>
  <!-- <el-table :data="previewTableData" style="width: 100%;margin-top: -15px;" height="300">
    <el-table-column label="数据预览(仅显示前十条数据)" align='center'>
      <el-table-column prop="id" label="*实体业务ID" width="100" />
      <el-table-column prop="name" label="*实体名称" width="100" />
      <el-table-column prop="classifyName" label="分类名称" width="100" />
      <el-table-column prop="classifyCode" label="*分类码" />
      <el-table-column prop="regionName" label="所属行政区" width="80" />
      <el-table-column prop="regionCode" label="*行政区划码" width="80" />
      <el-table-column prop="des" label="区域范围说明" />
      <el-table-column prop="lon" label="*经度" width="100" />
      <el-table-column prop="lat" label="*纬度" width="100" />
      <el-table-column prop="alt" label="高程" />
      <el-table-column prop="addition" label="备注" />
    </el-table-column>
  </el-table> -->
  <Table :columns="columns" :data="previewTableData" height="300" />
</template>
